<template>
  <div>
    <a-input-search
      v-model="selectedProjectName"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch">
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="modalTitle"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :class="'jee-outer-modal'">
      
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24" style="margin-bottom: 8px">
              <a-col :md="8" :sm="24">
                <a-form-item label="项目名称">
                  <a-input placeholder="请输入项目名称" v-model="queryParam.projectName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="项目状态">
                  <a-select
                    placeholder="请选择项目状态"
                    v-model="queryParam.status"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option :value="'0'">未开始</a-select-option>
                    <a-select-option :value="'1'">进行中</a-select-option>
                    <a-select-option :value="'2'">已完成</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="省份">
                  <a-select
                    placeholder="请选择省份"
                    v-model="queryParam.provinceCode"
                    @change="handleProvinceChange"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in provinceOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="margin-bottom: 8px">
              <a-col :md="8" :sm="24">
                <a-form-item label="城市">
                  <a-select
                    placeholder="请选择城市"
                    v-model="queryParam.cityCode"
                    @change="handleCityChange"
                    :disabled="!queryParam.provinceCode"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in cityOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="区县">
                  <a-select
                    placeholder="请选择区县"
                    v-model="queryParam.areaCode"
                    :disabled="!queryParam.cityCode"
                    :getPopupContainer="getParentModal"
                    allowClear
                  >
                    <a-select-option v-for="(name, code) in areaOptions" :key="code" :value="code">
                      {{ name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label=" ">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                  </span>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        
        <!-- 表格区域 -->
        <div style="margin-bottom: 10px;">
          <a-button type="primary" icon="plus" @click="handleAddProject">新增项目</a-button>
        </div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox' : 'radio'}"
          :scroll="{x: 'max-content'}"
          class="j-table-force-nowrap"
          @change="handleTableChange">
          
          <!-- 状态字段的自定义渲染 -->
          <template slot="statusSlot" slot-scope="text">
            <a-tag v-if="text == '0'" color="blue">未开始</a-tag>
            <a-tag v-else-if="text == '1'" color="green">进行中</a-tag>
            <a-tag v-else-if="text == '2'" color="orange">已完成</a-tag>
            <span v-else>{{ text }}</span>
          </template>
        </a-table>
      </a-spin>
    </a-modal>

    <!-- 新增项目模态框 -->
    <project-modal ref="projectModal" @ok="handleProjectCreated"></project-modal>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import ProjectModal from '@/views/crm/modules/ProjectModal'
  
  export default {
    name: 'JSelectProjectModal',
    components: {
      ProjectModal
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请选择项目'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      modalWidth: {
        type: Number,
        default: 800
      },
      multiple: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '选择项目'
      },
      customerId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        selectedRowKeys: [],
        selectedProjectId: '', // 保存选择的工程ID
        selectedProjectName: '', // 保存选择的工程名称
        selectedProject: null, // 保存选择的工程信息
        
        // 查询条件
        queryParam: {
          projectName: '',
          status: '',
          customerId: '',
          provinceCode: '',
          cityCode: '',
          areaCode: ''
        },
        
        // 省市区数据
        provinceOptions: {},
        cityOptions: {},
        areaOptions: {},
        
        // 数据源
        dataSource: [],
        
        // 表格列
        columns: [
          {
            title: '项目名称',
            dataIndex: 'projectName',
            width: '25%',
            align: 'center'
          },
          {
            title: '负责人',
            dataIndex: 'contactPerson',
            width: '20%',
            align: 'center'
          },
          {
            title: '项目地区',
            dataIndex: 'projectArea',
            width: '20%',
            align: 'center',
            customRender: (text, record) => {
              return [record.provinceName, record.cityName, record.areaName].filter(Boolean).join(' / ');
            }
          },
          {
            title: '项目状态',
            dataIndex: 'status',
            width: '10%',
            align: 'center',
            scopedSlots: { customRender: 'statusSlot' }
          }
        ],
        
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        
        loading: false,
        url: {
          list: '/crm/project/list',
          getById: '/crm/project/queryById',
          getByCustomerId: '/crm/project/getByCustomerId'
        }
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val) {
            this.initSelectedProject(val);
          } else {
            this.selectedProjectId = '';
            this.selectedProjectName = '';
            this.selectedProject = null;
            this.selectedRowKeys = [];
          }
        }
      },
      customerId: {
        immediate: true,
        handler(val) {
          if (val) {
            this.queryParam.customerId = val;
          } else {
            this.queryParam.customerId = '';
          }
        }
      }
    },
    mounted() {
      // 获取省份列表
      this.loadProvinceData();
    },
    methods: {
      // 初始化已选择的工程信息
      initSelectedProject(selectedId) {
        if (!selectedId) return;
        
        this.loading = true;
        getAction(this.url.getById, { id: selectedId }).then(res => {
          if (res.success) {
            this.selectedProject = res.result;
            this.selectedProjectId = this.selectedProject.id;
            this.selectedProjectName = this.selectedProject.projectName;
            this.selectedRowKeys = [this.selectedProjectId];
            
            // 移除初始化省市区数据的代码
            // 保持与onSelectChange方法一致，不自动填充查询条件
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 打开选择框
      handleSearch() {
        if (this.disabled) return;
        
        this.visible = true;
        
        // 确保每次打开时都设置最新的客户ID
        if (this.customerId) {
          this.queryParam.customerId = this.customerId;
          console.log('使用客户ID查询项目：', this.customerId);
        }
        
        this.loadData(1);
      },
      
      // 加载数据
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        
        const params = this.getQueryParams();
        this.loading = true;
        
        // 如果有客户ID，优先使用按客户ID查询的API
        let apiUrl = this.url.list;
        if (this.customerId && this.queryParam.customerId) {
          apiUrl = this.url.getByCustomerId;
          // 根据客户ID查询时，直接传递客户ID参数
          getAction(apiUrl, { customerId: this.queryParam.customerId }).then(res => {
            if (res.success) {
              // getByCustomerId返回的是数组而非分页对象
              this.dataSource = res.result || [];
              this.ipagination.total = this.dataSource.length || 0;
            }
          }).finally(() => {
            this.loading = false;
          });
        } else {
          // 使用标准列表查询API（分页）
          getAction(apiUrl, params).then(res => {
            if (res.success) {
              this.dataSource = res.result.records || [];
              this.ipagination.total = res.result.total || 0;
            }
          }).finally(() => {
            this.loading = false;
          });
        }
      },
      
      // 获取查询参数
      getQueryParams() {
        const param = Object.assign({}, this.queryParam);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
      
      // 选择改变
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        
        if (!this.multiple) {
          this.selectedProject = selectedRows[0];
          
          // 移除自动填充省市区信息的代码
          // 选择工程时不应该影响已有的查询条件
        } else {
          // 多选模式
          this.selectedProject = selectedRows;
        }
      },
      
      // 查询按钮
      searchQuery() {
        this.loadData(1);
      },
      
      // 重置按钮
      searchReset() {
        // 保存当前客户ID
        const currentCustomerId = this.customerId || this.queryParam.customerId;
        
        this.queryParam = {
          projectName: '',
          status: '',
          customerId: currentCustomerId, // 保留客户ID
          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined
        };
        this.cityOptions = {};
        this.areaOptions = {};
        this.loadData(1);
      },
      
      // 表格分页、排序、筛选变化
      handleTableChange(pagination, filters, sorter) {
        this.ipagination.current = pagination.current;
        this.ipagination.pageSize = pagination.pageSize;
        this.loadData();
      },
      
      // 确定按钮
      handleOk() {
        if (!this.selectedProject) {
          this.$message.warning('请选择项目');
          return;
        }
        
        if (!this.multiple) {
          this.selectedProjectId = this.selectedProject.id;
          this.selectedProjectName = this.selectedProject.projectName;
          
          this.$emit('input', this.selectedProjectId);
          this.$emit('change', this.selectedProjectId, this.selectedProject);
        } else {
          // 多选模式
          const ids = this.selectedProject.map(item => item.id);
          const names = this.selectedProject.map(item => item.projectName);
          
          this.selectedProjectId = ids.join(',');
          this.selectedProjectName = names.join(',');
          
          this.$emit('input', this.selectedProjectId);
          this.$emit('change', this.selectedProjectId, this.selectedProject);
        }
        
        this.handleCancel();
      },
      
      // 取消按钮
      handleCancel() {
        this.visible = false;
        
        // 重置查询条件，但保留客户ID
        const currentCustomerId = this.customerId || this.queryParam.customerId;
        this.queryParam = {
          projectName: '',
          status: '',
          customerId: currentCustomerId,
          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined
        };
        this.cityOptions = {};
        this.areaOptions = {};
      },
      
      // 加载省份数据
      loadProvinceData() {
        this.provinceOptions = this.$Jpcaa['86'] || {};
      },
      
      // 处理省份选择变更
      handleProvinceChange(value) {
        // 清空市和区的选择
        this.queryParam.cityCode = undefined;
        this.queryParam.areaCode = undefined;
        this.areaOptions = {};
        
        if (value) {
          // 加载该省份下的城市
          this.cityOptions = this.$Jpcaa[value] || {};
        } else {
          this.cityOptions = {};
        }
      },
      
      // 处理城市选择变更
      handleCityChange(value) {
        // 清空区的选择
        this.queryParam.areaCode = undefined;
        
        if (value) {
          // 加载该城市下的区县
          this.areaOptions = this.$Jpcaa[value] || {};
        } else {
          this.areaOptions = {};
        }
      },
      
      // 获取父级Modal元素，解决下拉框被遮挡的问题
      getParentModal() {
        return document.querySelector('.jee-outer-modal');
      },
      
      // 新增项目按钮
      handleAddProject() {
        if (this.customerId) {
          // 如果有客户ID，传递给项目模态框
          this.$refs.projectModal.show({customerId: this.customerId});
        } else {
          this.$refs.projectModal.show();
        }
      },
      
      // 新增项目成功后的处理
      handleProjectCreated() {
        this.loadData(1);
      }
    },
    computed: {
      modalTitle() {
        if (this.customerId) {
          return '选择客户下的项目';
        }
        return this.title || '选择项目';
      }
    }
  }
</script>

<style scoped>
  .query-area {
    margin-bottom: 16px;
    background-color: #fafafa;
    padding: 12px 16px 4px 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  }
  
  .table-page-search-submitButtons {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: flex-end;
    padding-top: 4px;
  }
  
  /* 查询按钮样式 */
  .table-page-search-submitButtons .ant-btn {
    height: 32px;
    line-height: 32px;
    padding: 0 15px;
  }
  
  /* 表单项样式优化 */
  ::v-deep .ant-form-item {
    margin-bottom: 8px;
    width: 100%;
  }
  
  ::v-deep .ant-form-inline .ant-form-item {
    display: flex;
    margin-right: 0;
  }
  
  ::v-deep .ant-form-item-label {
    line-height: 32px;
    min-width: 70px;
    width: 70px;
    text-align: right;
    padding-right: 8px;
    white-space: nowrap;
    display: inline-block;
    flex-shrink: 0;
  }
  
  ::v-deep .ant-form-item-control-wrapper {
    flex: 1;
    width: calc(100% - 70px);
  }
  
  ::v-deep .ant-form-item-control {
    line-height: 32px;
    flex: 1;
  }
  
  ::v-deep .ant-select {
    width: 100%;
    height: 32px;
  }
  
  ::v-deep .ant-input {
    width: 100%;
    height: 32px;
  }
  
  /* 确保所有控件高度一致 */
  ::v-deep .ant-select-selection--single {
    height: 32px;
  }
  
  ::v-deep .ant-select-selection__rendered {
    line-height: 30px;
  }
  
  /* 表格样式优化 */
  ::v-deep .ant-table-wrapper {
    margin-top: 8px;
  }
  
  ::v-deep .ant-table-bordered .ant-table-thead > tr > th {
    background-color: #fafafa;
  }
  
  /* 确保每行表单项布局一致 */
  ::v-deep .ant-row {
    display: flex;
    flex-wrap: wrap;
  }
  
  /* 调整label为空的表单项，使其对齐 */
  ::v-deep .ant-form-item-label > label:empty {
    display: none;
  }
  
  ::v-deep .ant-form-item-label > label:empty + .ant-form-item-children {
    padding-top: 4px; /* 微调使按钮与输入框对齐 */
  }
  
  /* 表格横向滚动样式 */
  ::v-deep .ant-table-wrapper {
    overflow-x: auto;
  }
  
  ::v-deep .ant-table-body {
    overflow-x: auto !important;
  }
  
  /* 适配小屏幕设备 */
  @media screen and (max-width: 1200px) {
    ::v-deep .ant-table-content {
      overflow-x: auto;
    }
    
    ::v-deep .ant-form-item-label {
      width: 65px;
      min-width: 65px;
    }
    
    ::v-deep .ant-form-item-control-wrapper {
      width: calc(100% - 65px);
    }
  }
  
  @media screen and (max-width: 576px) {
    ::v-deep .ant-col-sm-24 {
      padding-right: 0 !important;
      padding-left: 0 !important;
    }
    
    ::v-deep .ant-form-item-label {
      width: 60px;
      min-width: 60px;
    }
    
    ::v-deep .ant-form-item-control-wrapper {
      width: calc(100% - 60px);
    }
  }
</style> 